package core

import (
	"fmt"
	"os"
	"strings"
	"wave-admin/global"

	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

func InitViper() *viper.Viper {
	workDir, _ := os.Getwd()
	content, err := os.ReadFile(workDir + "/.env")
	if err != nil {
		fmt.Println("Fatal error .env file: ", err)
	}
	contentText := string(content)
	// 去除空格
	contentText = strings.Replace(contentText, " ", "", -1)
	// 去除换行符
	contentText = strings.Replace(contentText, "\n", "", -1)
	arr := strings.Split(contentText, "=")

	configName := "application"
	if arr[1] == "docker" {
		configName = "application-docker"
	}

	v := viper.New()
	v.SetConfigName(configName)
	v.SetConfigType("yaml")
	v.AddConfigPath(workDir + "/config")
	err = v.ReadInConfig()
	if err != nil {
		fmt.Println("Fatal error config file: ", err)
	}
	v.WatchConfig()

	v.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("config file changed: ", e.Name)
		if err := v.Unmarshal(&global.GnConfig); err != nil {
			fmt.Println(err)
		}
	})
	if err := v.Unmarshal(&global.GnConfig); err != nil {
		fmt.Println(err)
	}
	return v
}
